from rest_framework.views import APIView
from api.serializers import *
from core.decorator.checkHttp import headerChecking
from core.token.token_cache import Token_Cache,timedelta,datetime
from core.token.token_event import TOKEN_EVENT
from core.config import REQUEST_MANAGER,cfg
from core.decorator.salt import slat
from core.general.crypto import CRYPTO
class ticket(APIView):
    @headerChecking(["data.app_id","data.secret","data.sign"])
    @slat
    def post(self,request):
        app_id= request.data.get("app_id")
        secret= request.data.get("secret")
        if cfg.APP_ID == app_id and cfg.APP_SECRET == secret:
            state, data= Token_Cache.auto_generate_token(
                expire= datetime.now().__add__(timedelta(minutes=cfg.TOKEN_EXPIRE_TIME/60)),
                event= TOKEN_EVENT.APP_ACCESS,
                union_field= app_id,
                remote_ip=REQUEST_MANAGER.getRemoteAddr(request),hash_str= secret
            )
            if state:
                m_data= {
                    "token":data["token"],
                    "expire":data["expire"]
                }
                return Response(stateCode=200, data= m_data)
            else:
                return Response(stateCode=-1, data= data.args)
        else:
            return Response(stateCode= -1, data= "app id or secret error.")
        
    def get(self,request):
        o= datetime.now().strftime("%Y/%m%d")        
        return CRYPTO.md5([cfg.APP_ID,cfg.APP_SECRET,cfg.SERVICE_KEY,cfg.SERVICE_ACCESS_SECRET,o])
         
#class signature